/**
 * 
 */
package trungsi.gea.photos.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FacebookWebappHelper;

/**
 * @author trungsi
 *
 */
public class FacebookFilter implements Filter {

	private String apiKey;
	private String secret;
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		try {  
            HttpServletRequest request = (HttpServletRequest)req;
            HttpServletResponse response = (HttpServletResponse)res;
            
            HttpSession session = request.getSession(true);
            FacebookJsonRestClient userClient = getUserClient(session); 
            
            FacebookWebappHelper<Object> facebook = new FacebookWebappHelper<Object>(request, response, apiKey, secret, userClient);
            String nextPage = request.getRequestURI();
            System.out.println("contextPath=" + request.getContextPath());
            System.out.println("requestURL=" + request.getRequestURL());
            if (!request.getContextPath().equals("")) {
            	nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); //cut out the first /, the context path and the 2nd /
            }
            System.out.println(nextPage);
            boolean redirectOccurred = facebook.requireLogin(nextPage);
            System.out.println(redirectOccurred);
            if(redirectOccurred) {
                    return;
            }
            redirectOccurred = facebook.requireFrame(nextPage);
            System.out.println(redirectOccurred);
            if(redirectOccurred) {
                    return;
            }
            
            try {
                userClient.users_getLoggedInUser();
                session.setAttribute("facebook.session.key", userClient.getCacheSessionKey());
                FacebookClientHolder.setFacebookClient(userClient);
            } catch(FacebookException ex) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while fetching user's facebook ID");
                return;
            }
            
            System.out.println("dofilter");
            chain.doFilter(request, response);
    } finally {
    }
	}
	
	public FacebookJsonRestClient getUserClient(HttpSession session) {
		String sessionKey = (String) session.getAttribute("facebook.session.key");
		return sessionKey != null ? new FacebookJsonRestClient(apiKey, secret, sessionKey)
			: new FacebookJsonRestClient(apiKey, secret);
    }
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		apiKey = fConfig.getServletContext().getInitParameter("apiKey");
		secret = fConfig.getServletContext().getInitParameter("secret");
	}
}
